package org.example.spring03tx.dao;

import org.example.spring03tx.bean.Book;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/*按照id查图书*/
@Component
public class BookDao {
    @Autowired
    JdbcTemplate jdbcTemplate;
   public  Book getBookById(Integer id){
       //1.查询图书sql
       String sql = "select * from book where id = ?";

       //2.执行查询
       Book book = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(Book.class), id);
       return  book;
    }

    /*添加图书*/
    public void addBook(Book book){
       String sql = "insert into book(bookName,price,stock) values(?,?,?)";
       jdbcTemplate.update(sql,book.getBookName(),book.getPrice(),book.getStock());
    }

    /*按照id修改图书库存
    * num：用户买走的图书数量*/
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void updateBookStock(Integer id,Integer num){
        String sql = "update book set stock = stock - ? where id = ?";
        jdbcTemplate.update(sql,num,id);
    }

    /*按照id删除图书*/
    public void deleteBook(Integer id){
        String sql = "delete from book where id = ?";
        jdbcTemplate.update(sql,id);
    }

    /*按照id查询图书价格*/
//    @Transactional(isolation = Isolation.READ_UNCOMMITTED)//读未提交
//    @Transactional(isolation = Isolation.REPEATABLE_READ)//可重复读 快照读 ——>MYSQL默认级别
    @Transactional(isolation = Isolation.READ_COMMITTED)//读已提交 ——>Oracle默认级别
    public BigDecimal getBookPriceById(Integer id){
        String sql = "select price from book where id = ?";
        BigDecimal price = jdbcTemplate.queryForObject(sql, BigDecimal.class, id);
        return price;
    }
}
